package com.xpec.cipher.handler;

import com.xpec.cipher.CipherHandler;
import com.xpec.cipher.tals.TalsConstance;
import com.xpec.cipher.tals.record.ChangeCipherSpecRecord;

public class ServerChangeCipherHandler implements CipherConnectionPacketHandler
{

	@Override
	public void receiveHandle(CipherHandler cipherHandler)
	{

		int contentType = cipherHandler.readUnsignedByteFromRealContent();
		if (contentType == TalsConstance.CONTENT_TYPE_CHANGE_CIPHER_SPEC)
		{
			int remainSize = cipherHandler.getRealContentRemain();
			if (remainSize != TalsConstance.CHANGE_CIPHER_VERIFY_DATA_SIZE)
			{
				throw new IllegalStateException("Change cipher verify data's size must be "
						+ TalsConstance.CHANGE_CIPHER_VERIFY_DATA_SIZE + " bytes! But it is "
						+ remainSize + " bytes in fact!");
			}
			byte[] verifyData = new byte[TalsConstance.CHANGE_CIPHER_VERIFY_DATA_SIZE];
			cipherHandler.readByteFromRealContent(verifyData);
			ChangeCipherSpecRecord record = new ChangeCipherSpecRecord(verifyData);

			cipherHandler.sendData(record.resolve(), true);
			cipherHandler.notifyCipherFinished();
			
		}
	}

	@Override
	public void sendHandle(CipherHandler cipherHandler)
	{
		cipherHandler.passMessage(CipherHandler.PASS_MESSAGE_SEND);
	}

}
